package com.taoym.voucher.admin;

import cn.hutool.core.util.RandomUtil;
import com.taoym.voucher.admin.domain.SysUser;
import com.taoym.voucher.admin.mapper.SysUserMapper;
import com.taoym.voucher.common.utils.SecureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Properties;

/**
 * @coder taoym
 * @datetime 2021/9/27 16:54
 * @desc 初始化加密key和管理员用户信息
 */
@Component
@Order(1)
@Slf4j
public class ApplicationInitRunner implements ApplicationRunner {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        String profile = System.getProperty("user.dir") + "\\common\\src\\main\\resources\\profile.properties";

        Properties properties = new Properties();
        BufferedReader reader = new BufferedReader(new FileReader(profile));
        properties.load(reader);
        reader.close();
        String secureUtilsKey = properties.getProperty("SecureUtils.key");
        if (ObjectUtils.isEmpty(secureUtilsKey)) {
            secureUtilsKey = RandomUtil.randomString(13);
            log.info("random secure key is {}", secureUtilsKey);
            properties.setProperty("SecureUtils.key", secureUtilsKey);
            BufferedWriter writer = new BufferedWriter(new FileWriter(profile));
            properties.store(writer, "init profile properties value");
            writer.close();
            SysUser sysUser = new SysUser();
            sysUser.setUsername("admin123");
            sysUser.setPassword(SecureUtils.encode("admin123"));
            sysUserMapper.insert(sysUser);
        }
        String jwtTokenUtilsKey = properties.getProperty("JwtTokenUtils.key");
        if (ObjectUtils.isEmpty(jwtTokenUtilsKey)) {
            jwtTokenUtilsKey = RandomUtil.randomString(10);
            log.info("random jwt key is {}", jwtTokenUtilsKey);
            properties.setProperty("JwtTokenUtils.key", jwtTokenUtilsKey);
            BufferedWriter writer = new BufferedWriter(new FileWriter(profile));
            properties.store(writer, "update" + jwtTokenUtilsKey + "value");
            writer.close();
        }
    }
}
